package utils

import (
	"math"
)

const (
	x_pi = math.Pi * 3000.0 / 180.0
	a    = 6378245.0
	ee   = 0.00669342162296594323
)

// WGS84ToGCJ02 將将 WGS84 坐標轉換爲 GCJ-02 坐標
func WGS84ToGCJ02(wgLon, wgLat float64) (mgLon, mgLat float64) {
	if outOfChina(wgLon, wgLat) {
		mgLon, mgLat = wgLon, wgLat
		return
	}
	dLon := transformLon(wgLon-105.0, wgLat-35.0)
	dLat := transformLat(wgLon-105.0, wgLat-35.0)
	radLat := wgLat / 180.0 * math.Pi
	magic := math.Sin(radLat)
	magic = 1 - ee*magic*magic
	sqrtMagic := math.Sqrt(magic)
	dLon = (dLon * 180.0) / (a / sqrtMagic * math.Cos(radLat) * math.Pi)
	dLat = (dLat * 180.0) / ((a * (1 - ee)) / (magic * sqrtMagic) * math.Pi)
	mgLon = wgLon + dLon
	mgLat = wgLat + dLat
	return
}

func transformLon(x, y float64) float64 {
	ret := 300.0 + x + 2.0*y + 0.1*x*x + 0.1*x*y + 0.1*math.Sqrt(math.Abs(x))
	ret += (20.0*math.Sin(6.0*x*math.Pi) + 20.0*math.Sin(2.0*x*math.Pi)) * 2.0 / 3.0
	ret += (20.0*math.Sin(x*math.Pi) + 40.0*math.Sin(x/3.0*math.Pi)) * 2.0 / 3.0
	ret += (150.0*math.Sin(x/12.0*math.Pi) + 300.0*math.Sin(x/30.0*math.Pi)) * 2.0 / 3.0
	return ret
}

func transformLat(x, y float64) float64 {
	ret := -100.0 + 2.0*x + 3.0*y + 0.2*y*y + 0.1*x*y + 0.2*math.Sqrt(math.Abs(x))
	ret += (20.0*math.Sin(6.0*x*math.Pi) + 20.0*math.Sin(2.0*x*math.Pi)) * 2.0 / 3.0
	ret += (20.0*math.Sin(y*math.Pi) + 40.0*math.Sin(y/3.0*math.Pi)) * 2.0 / 3.0
	ret += (160.0*math.Sin(y/12.0*math.Pi) + 320*math.Sin(y*math.Pi/30.0)) * 2.0 / 3.0
	return ret
}

func outOfChina(lon, lat float64) bool {
	if lon < 72.004 || lon > 137.8347 {
		return true
	}
	if lat < 0.8293 || lat > 55.8271 {
		return true
	}
	return false
}

func main() {
	// 示例使用 以北京天安门为例
	wgsLon, wgsLat := 116.39748176398996, 39.90892080127466
	gcjLon, gcjLat := WGS84ToGCJ02(wgsLon, wgsLat)
	println("GCJ-02 坐标:", gcjLon, gcjLat)
}
